package constants.system;

import com.alibaba.fastjson.JSONObject;
import constants.api.ApiResultBean;
import play.PlayPlugin;
import play.i18n.Messages;
import play.mvc.Http;
import play.mvc.results.*;
import org.eclipse.jdt.core.IField;
import utils.RequestHelper;

import java.lang.reflect.Method;

/**
 * @author yangzhi
 * @date 2018/12/10
 */
public class AuthorizationPlugin extends PlayPlugin {


	@Override
	public void beforeActionInvocation(Method actionMethod) {
		if(!actionMethod.isAnnotationPresent(GuestAuthorization.class)){
			//判断权限
			if (!RequestHelper.isAjaxQequest()) {
				//普通连接跳转
				checkAuthorization(actionMethod);
			}else{
				MemberShip member = MemberShip.current();
				Boolean guest = member.isGuest();
				if(guest) {
					String loginPath = RequestHelper.getRouterUrl("@@{UserController.login}");
					JSONObject result = new JSONObject();
					result.put("redirectUrl",loginPath);
					ApiResultBean bean = new ApiResultBean();
					bean.code = 401;
					bean.msg = "登录失效,请重新登录";
					bean.count=0;
					bean.data = result;
					throw new RenderJson(bean);
				}
			}
		}
	}

	/**
	 * 检查用户是否已授权可以调用方法
	 *
	 * @param method
	 */
	private void checkAuthorization(Method method){
		MemberShip member = MemberShip.current();
		Boolean guest = member.isGuest();
		if(guest){
			//跳转到登陆
			String loginPath = RequestHelper.getRouterUrl("@@{UserController.login}");
			if (!method.getName().equals("index")){
				loginPath = loginPath+"?isTop=1";
			}
			redirectToLogin(loginPath);
		}
	}

	/**
	 * 跳转到登录页面
	 *
	 * @param backUrl 登录成功后跳回请求系统的地址
	 */
	public static void redirectToLogin(String backUrl) {
		throw new Redirect(backUrl);
	}

}
